package com.sxhuayuan.parking.task;

import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.MonthlyProfit;
import com.sxhuayuan.parking.service.*;
import com.sxhuayuan.parking.service.impl.AgentServiceImpl;
import com.sxhuayuan.parking.service.impl.MonthlyProfitServiceImpl;
import com.sxhuayuan.parking.service.impl.ProfitStatisticsServiceImpl;
import com.sxhuayuan.parking.utils.DateUtils;
import com.sxhuayuan.parking.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.util.List;

/**
 * 代理分润月结算任务
 * 
 * @author 何龙
 * @create 2019-05-22 17:16
 */
public class MonthlyProfitTask implements Runnable {
	Logger log = LoggerFactory.getLogger(ProfitStatisticsTask.class);

	/** 统计的年月 yyyy-MM */
	private LocalDate month;

	AgentService agentService;
	MonthlyProfitService service;
	ProfitStatisticsService statisticsService;

	public MonthlyProfitTask(LocalDate month) {
		super();
		this.month = DateUtils.getMinDate(month);
	}

	@Override
	public void run() {
		init();
		agentMonthProfitStatisticsJob();
	}

	/**
	 * 以月份来统计代理分润
	 */
	private void agentMonthProfitStatisticsJob() {
		List<Agent> agents = agentService.findAll();
		for (Agent agent : agents) {
			MonthlyProfit monthlyProfit = statisticsService.countByAgentAndMonth(agent, month);
			service.save(monthlyProfit);
		}
	}

	private void init() {
		agentService = SpringUtils.getBean("agentServiceImpl", AgentServiceImpl.class);
		service = SpringUtils.getBean("monthlyProfitServiceImpl", MonthlyProfitServiceImpl.class);
		statisticsService = SpringUtils.getBean("profitStatisticsServiceImpl", ProfitStatisticsServiceImpl.class);
	}

}
